package com.geekyang.rabbitmqapi.exchange.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author geekyang
 * @date 2018/10/8 21:24
 */
public class ConsumerDirectExchange {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        // 1.创建 ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("39.106.128.50");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);

        // 2.创建 Connection
        Connection connection = connectionFactory.newConnection();

        // 3.创建 Channel
        Channel channel = connection.createChannel();

        // 4.声明
        String exchangeName = "test_direct_exchange";
        String exchangeType = "direct";
        String queueName = "test_direct_queue";
        String routingKey = "test.direct";
        // 声明一个交换机
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
        // 声明一个队列
        channel.queueDeclare(queueName, false, false, false, null);
        // 声明一个绑定
        channel.queueBind(queueName, exchangeName, routingKey);

        // 5.创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        // 设置channel: 队列名称， 是否自动ACK， Consumer
        channel.basicConsume(queueName, true, queueingConsumer);

        // 循环获取消息
        while(true){
            // 获取消息，如果没有消息，会一直阻塞
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("收到消息：" + msg);
        }


    }

}
